;==============================================================================;
;; Kload
;; tools : nasm
;; comments:
;; 0. Set PIC Disable and Command CLI
;; 1. Set A20 Line Enable
;; 2. Relocation Kernel
;; 3. LGDT/LIDT
;; 4. Go Into Protected Mode
;; 5. Jump into Kernel
;==============================================================================;

	ORG	0
	BITS	16

	JMP ENTRY
;------------------------------------------------------------------------------;
; Data
S_INTRO	DB "AilenoS has gone into the Kload, ailenos's kernel loader.",0
S_A20	DB "AilenoS can access the memory positioned 1Megabytes and more.",0
;------------------------------------------------------------------------------;
;------------------------------------------------------------------------------;
; Function(16bit)
P16:	PUSHA
LP_P16:	MOV AH, BYTE[DS:SI]
	MOV BYTE[ES:DI], AH
	INC SI
	INC DI
	MOV BYTE[ES:DI], 0x0B
	INC DI
	TEST AH,AH
	JNZ LP_P16
	POPA
	RET
;------------------------------------------------------------------------------;
; Set A20 Line ( By Kawai Hidemi's Book )
SET_A20:
	PUSHA
	CALL wait_kbd
	MOV AL, 0xd1
	OUT 0x64, AL  ; write output
	CALL wait_kbd
	MOV AL, 0xdf
	OUT 0x60, AL  ; enable A20
	CALL wait_kbd
	POPA
	RET
;------------------------------------------------------------------------------;
wait_kbd:
	IN AL, 0x64
	AND AL, 0x02
	IN AL, 0x60
	JNZ wait_kbd
	RET
;------------------------------------------------------------------------------;
STOP_INT:
	PUSHA
	MOV AL, 0xff
	OUT 0x21, AL
	NOP	; some PICs don't work when I command 'OUT' twice at once 
	OUT 0xa1, AL
	CLI	; also stop interrupting at CPU
	POPA
	RET
;------------------------------------------------------------------------------;
LOCATE_KNL:
	PUSHA
	; TODO : Get the Kernel Position
	; and use rep movsw.

	POPA
	RET
;------------------------------------------------------------------------------;
; EntryPoint
ENTRY:	MOV AX, CS
	MOV DS, AX
	;MOV ES, AX	; do NOT change extra segments for Video Memory.
	MOV FS, AX
	MOV GS, AX
	;MOV SS, AX	; do NOT change stack segments.

	MOV DI, 80*2*3
	MOV SI, S_INTRO
	CALL P16

	CALL STOP_INT

	CALL SET_A20

	MOV DI, 80*2*4
	MOV SI, S_A20
	CALL P16

	CALL LOCATE_KNL

	HLT
;------------------------------------------------------------------------------;
; End of Code.